﻿using AnesSystem.Controls;
using AnesSystem.Models;
using AnesSystem.Services;
using AnesSystem.Util;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Common;

namespace AnesSystem.ViewModels
{
    public class PacuSingleDrugConfigCtrlViewModel : BaseViewModel<PacuSingleDrugConfigCtrlViewModel>
    {
        #region Variables
        private PatientDrugsModel _patientDrugsModel;
        private PatientDrugsModel _patientDrugsModelCopy;
        private ObservableCollection<SingleDrugElementCtrl> _ctrlList;
        private ConfigDrugMethodsModel _selectedDrugMethod;
        private List<ConfigDrugMethodsModel> _configDrugMethodsModelList;
        private ConfigDrugsModel _selectedDrug;


        private List<CustomEDBtnCtrl> _displayDrugCtrlList;
        private Dictionary<string, List<ConfigDrugsModel>> _drugList;
        private ObservableCollection<ConfigDrugGroupTypesModel> _drugTypeGroupList;
        private Dictionary<string, List<CustomEDBtnCtrl>> _drugCtrlList;
        private ObservableCollection<CommonTypeCellCtrl> _drugTypeCtrlList;
        private CommonTypeCellCtrl _currentSelType;

        private Visibility _deleteButtonVisibility;
        private Visibility _saveAndContinueButtonVisibility;
        #endregion

        #region Constructor
        public PacuSingleDrugConfigCtrlViewModel()
        {
            _patientDrugsModelCopy = new PatientDrugsModel();
            _ctrlList = new ObservableCollection<SingleDrugElementCtrl>();
            _selectedDrugMethod = new ConfigDrugMethodsModel();
            _configDrugMethodsModelList = DataManager.Instance.ConfigDrugMethodsModelList.ToList().Where(O => O.Single == true).ToList();

            _displayDrugCtrlList = new List<CustomEDBtnCtrl>();
            _drugList = new Dictionary<string, List<ConfigDrugsModel>>();
            _drugTypeGroupList = new ObservableCollection<ConfigDrugGroupTypesModel>();
            _drugCtrlList = new Dictionary<string, List<CustomEDBtnCtrl>>();
            _drugTypeCtrlList = new ObservableCollection<CommonTypeCellCtrl>();
            _currentSelType = new CommonTypeCellCtrl();

            DeleteButtonVisibility = Visibility.Hidden;
            SaveAndContinueButtonVisibility = Visibility.Hidden;

            InitialDrugTypeList();
            InitialDrugList();
            CreateDrugTypeGroupCtrlList();
            if (HospitalConfig.Instance.CurrentHospital.HospitalCode.Equals(HospitalConfig.HOSPITAL_CODE_SC_CD_TYFSYY))
            {
                if (_drugTypeGroupList.Where(O => O.Code != null && O.Code.Equals("drugGroupType_1")).ToList() != null &&
                    _drugTypeGroupList.Where(O => O.Code != null && O.Code.Equals("drugGroupType_1")).ToList().Count > 0)
                {
                    SelectedDrugGroupType = _drugTypeGroupList.Where(O => O.Code != null && O.Code.Equals("drugGroupType_1")).ToList().First();
                }
            }
            else
            {
                if (_drugTypeGroupList.Where(O => O.Code != null && O.Code.Equals("drugGroupType_2")).ToList() != null &&
                    _drugTypeGroupList.Where(O => O.Code != null && O.Code.Equals("drugGroupType_2")).ToList().Count > 0)
                {
                    SelectedDrugGroupType = _drugTypeGroupList.Where(O => O.Code != null && O.Code.Equals("drugGroupType_2")).ToList().First();
                }
            }
            GetDisplayDrugCtrlList(SelectedDrugGroupType.Code);
        }
        #endregion

        #region Properties

        public ConfigDrugGroupTypesModel SelectedDrugGroupType { get; set; }
        public PatientDrugsModel PatientDrugsModelCopy
        {
            get
            {
                return _patientDrugsModelCopy;
            }

            set
            {
                if (value == null) return;
                _patientDrugsModelCopy = value;
                RaisePropertyChanged("PatientDrugsModelCopy");
            }
        }

        public ObservableCollection<SingleDrugElementCtrl> CtrlList
        {
            get
            {
                return _ctrlList;
            }

            set
            {
                _ctrlList = value;
            }
        }

        public ConfigDrugMethodsModel SelectedDrugMethod
        {
            get
            {
                return _selectedDrugMethod;
            }

            set
            {
                _selectedDrugMethod = value;
                RaisePropertyChanged("SelectedDrugMethod");
            }
        }

        public List<ConfigDrugMethodsModel> ConfigDrugMethodsModelList
        {
            get
            {
                return _configDrugMethodsModelList;
            }

            set
            {
                _configDrugMethodsModelList = value;
                RaisePropertyChanged("ConfigDrugMethodsModelList");
            }
        }

        public ConfigDrugsModel SelectedDrug
        {
            get
            {
                return _selectedDrug;
            }

            set
            {
                _selectedDrug = value;
                RaisePropertyChanged("SelectedDrug");
            }
        }

        public List<CustomEDBtnCtrl> DisplayDrugCtrlList
        {
            get
            {
                return _displayDrugCtrlList;
            }

            set
            {
                _displayDrugCtrlList = value;
                RaisePropertyChanged("DisplayDrugCtrlList");
            }
        }

        public Dictionary<string, List<ConfigDrugsModel>> DrugList
        {
            get
            {
                return _drugList;
            }

            set
            {
                _drugList = value;
                RaisePropertyChanged("DrugList");
            }
        }

        public ObservableCollection<ConfigDrugGroupTypesModel> DrugTypeGroupList
        {
            get
            {
                return _drugTypeGroupList;
            }

            set
            {
                _drugTypeGroupList = value;
            }
        }

        public Dictionary<string, List<CustomEDBtnCtrl>> DrugCtrlList
        {
            get
            {
                return _drugCtrlList;
            }

            set
            {
                _drugCtrlList = value;
                RaisePropertyChanged("DrugCtrlList");
            }
        }

        public ObservableCollection<CommonTypeCellCtrl> DrugTypeCtrlList
        {
            get
            {
                return _drugTypeCtrlList;
            }

            set
            {
                _drugTypeCtrlList = value;
            }
        }

        public CommonTypeCellCtrl CurrentSelType
        {
            get
            {
                return _currentSelType;
            }

            set
            {
                _currentSelType = value;
                RaisePropertyChanged("CurrentSelType");
            }
        }

        public PatientDrugsModel PatientDrugsModel
        {
            get
            {
                return _patientDrugsModel;
            }

            set
            {
                _patientDrugsModel = value;
                if (value != null)
                {
                    PatientDrugsModelCopy = value.ObjectToJsonM().JsonToObjectM<PatientDrugsModel>();
                }
                RaisePropertyChanged("PatientDrugsModel");
            }
        }

        public Visibility DeleteButtonVisibility
        {
            get
            {
                return _deleteButtonVisibility;
            }

            set
            {
                _deleteButtonVisibility = value;
                RaisePropertyChanged("DeleteButtonVisibility");
            }
        }

        public Visibility SaveAndContinueButtonVisibility
        {
            get
            {
                return _saveAndContinueButtonVisibility;
            }

            set
            {
                _saveAndContinueButtonVisibility = value;
                RaisePropertyChanged("SaveAndContinueButtonVisibility");
            }
        }


        #endregion

        #region 依赖属性

        #endregion

        #region Event

        #endregion

        #region Private Methods

        #endregion

        #region Public/Protected Methods
        public void AddSingleCtrl()
        {
            SingleDrugElementCtrl ctrl = new SingleDrugElementCtrl();
            ItemModel itemDrug = new ItemModel();
            ctrl.Item = itemDrug;
            PatientDrugsModelCopy.Drugs.Items.Add(itemDrug);
            ctrl.ConfigUnitsModelList = DataManager.Instance.ConfigUnitsModelList.ToList();
            CtrlList.Add(ctrl);
        }
        public void DelSingleCtrl(SingleDrugElementCtrl ctrl)
        {
            if (CtrlList.Count > 1)
            {
                CtrlList.Remove(ctrl);
                PatientDrugsModelCopy.Drugs.Items.Remove(ctrl.Item);
            }
        }
        public void AddDrug()
        {
            for (int i = 0; i < CtrlList.Count; i++)
            {
                if (CtrlList[i].Item == null || CtrlList[i].Item.Name.Equals("") || i == CtrlList.Count() - 1)
                {
                    ItemModel itemDrug = new ItemModel();
                    itemDrug.Code = SelectedDrug.Code;
                    itemDrug.Name = SelectedDrug.Name;
                    if (HospitalConfig.Instance.CurrentHospital.HospitalCode.Equals(HospitalConfig.HOSPITAL_CODE_SC_CD_TYFSYY) || HospitalConfig.Instance.CurrentHospital.HospitalCode.Equals(HospitalConfig.HOSPITAL_CODE_SC_SCDC))
                    {
                        itemDrug.Dose = SelectedDrug.Dose.ToString();
                    }
                    if (HospitalConfig.Instance.CurrentHospital.HospitalCode.Equals(HospitalConfig.HOSPITAL_CODE_CQ_NTZYY))
                    {
                        itemDrug.Unit = "ml";
                    }
                    else
                    {
                        try
                        {
                            ConfigUnitsModel unit = DataManager.Instance.ConfigUnitsModelList.ToList().Find(delegate (ConfigUnitsModel u) { return u.Code == SelectedDrug.UnitName; });
                            itemDrug.Unit = unit == null ? "ml" : unit.Name;
                        }
                        catch (Exception ex)
                        {
                            itemDrug.Unit = "ml";
                            Common.LogHelper.Error(this.GetType(), ex);
                        }
                    }
                    CtrlList[i].Item = itemDrug;
                    PatientDrugsModelCopy.Drugs.Items[i] = itemDrug;
                    break;
                }
            }
        }

        public void InitialDrugList()
        {
            var list = DataManager.Instance.ConfigDrugsModelList.GroupBy(O => O.DrugGroupTypeCode);
            foreach (var item in list)
            {
                if (!string.IsNullOrEmpty(item.Key) && !_drugList.ContainsKey(item.Key))
                {
                    _drugList.Add(item.Key, item.ToList());
                }
            }
        }

        private void InitialDrugTypeList()
        {
            foreach (var item in DataManager.Instance.ConfigDrugGroupTypesModelList.ToList())
            {
                if (!string.IsNullOrEmpty(item.Code))
                    _drugTypeGroupList.Add(item);
            }
        }

        private void CreateDrugTypeGroupCtrlList()
        {
            foreach (var item in _drugTypeGroupList)
            {
                CommonTypeCellCtrl ctrl = new CommonTypeCellCtrl();
                ctrl.PreviewMouseLeftButtonDown += Type_PreviewMouseLeftButtonDown;
                ctrl.Tag = item;
                ctrl.Group = "group";
                ctrl.Display = item.Name;
                ctrl.FontSize = 16;
                ctrl.Margin = new System.Windows.Thickness(10, 5, 10, 0);
                DrugTypeCtrlList.Add(ctrl);
            }
        }

        private void GetDisplayDrugCtrlList(string group)
        {
            if (!string.IsNullOrEmpty(group))
            {
                if (!_drugCtrlList.ContainsKey(group))
                {
                    if (!_drugList.ContainsKey(group)) return;
                    List<ConfigDrugsModel> list = _drugList[group];
                    List<CustomEDBtnCtrl> listCtrl = new List<CustomEDBtnCtrl>();
                    foreach (var item in list)
                    {
                        CustomEDBtnCtrl ctrl = new CustomEDBtnCtrl();
                        ctrl.Clicked += Ctrl_Clicked;
                        ctrl.MouseLeftButtonDown += Drug_MouseLeftButtonDown;
                        ctrl.Margin = new System.Windows.Thickness(5);
                        ctrl.Tag = item;
                        ctrl.Display = item.Name;
                        listCtrl.Add(ctrl);
                    }
                    _drugCtrlList.Add(group, listCtrl);
                    DisplayDrugCtrlList = listCtrl;
                }
                else
                {
                    DisplayDrugCtrlList = _drugCtrlList[group];
                }
            }
        }

        //给药赋值
        public void SetPatientDrug()
        {
            GetDisplayDrugCtrlList(SelectedDrugGroupType.Code);
            //赋值药的成分
            CtrlList.Clear();
            if (PatientDrugsModelCopy.PatientID == null)
            {
                AddSingleCtrl();
                DeleteButtonVisibility = Visibility.Hidden;
                SaveAndContinueButtonVisibility = Visibility.Visible;
            }
            else
            {
                foreach (var item in PatientDrugsModelCopy.Drugs.Items)
                {
                    SingleDrugElementCtrl singleCtrl = new SingleDrugElementCtrl();
                    singleCtrl.ConfigUnitsModelList = DataManager.Instance.ConfigUnitsModelList.ToList();
                    singleCtrl.Item = item;
                    CtrlList.Add(singleCtrl);
                }
                DeleteButtonVisibility = Visibility.Visible;
                SaveAndContinueButtonVisibility = Visibility.Hidden;
            }
            //赋值药的用药方法
            if (PatientDrugsModelCopy.DrugMethod == null || PatientDrugsModelCopy.DrugMethod.Equals(""))
            {
                PatientDrugsModelCopy.DrugMethod = Constants.DRUG_IV;
            }

            if (ConfigDrugMethodsModelList.Where(O => O.Name != null && O.Name.Equals(PatientDrugsModelCopy.DrugMethod)).ToList() != null &&
                ConfigDrugMethodsModelList.Where(O => O.Name != null && O.Name.Equals(PatientDrugsModelCopy.DrugMethod)).ToList().Count > 0)
            {
                SelectedDrugMethod = ConfigDrugMethodsModelList.Where(O => O.Name != null && O.Name.Equals(PatientDrugsModelCopy.DrugMethod)).ToList().First();
            }
        }


        //保存一条用药记录
        public bool SavePatientDrug()
        {
            if (CheckDrugTime())
            {
                PatientDrugsModelCopy.Single = true;
                PatientDrugsModelCopy.PatientID = DataManager.Instance.CurrentPatientLink.Id.ToString();
                PatientDrugsModelCopy.Type = Constants.DRUG_FUSU_SPECIAL;
                PatientDrugsModelCopy.DrugMethod = SelectedDrugMethod.Name;
                PatientDrugsModelCopy.Drugs.HashCode = (AnesRecordUtil.Instance.GetDrugHashCode(PatientDrugsModelCopy)).GetHashCode().ToString();
                PatientDrugsModelCopy.Drugs.FullName = AnesRecordUtil.Instance.GetDrugFullName(PatientDrugsModelCopy);
                PatientDrugsModelCopy.EndTime = PatientDrugsModelCopy.BeginTime;
                PatientDrugsModelCopy.Status = Constants.PatientDrugs_STATUS_FINISHED;
                OperationDataPool.Instance.CurOperationData.DrugsDataCache.AddAndUpdateExe(PatientDrugsModelCopy);
                RefreshYao();
                //OperationDetailsViewModel.Instance.Refresh();
                return true;
            }
            else
            {
                return false;
            }
        }

        public bool CheckDrugTime()
        {
            foreach (var item in PatientDrugsModelCopy.Drugs.Items)
            {
                if (null == item || string.IsNullOrEmpty(item.Code))
                {
                    MessageBoxCommon.ShowDialog("请输入药名", MessageBoxCommon.OK);
                    return false;
                }
            }
            if (PatientDrugsModelCopy.BeginTime != new DateTime() && PatientDrugsModelCopy.BeginTime.CompareTo(DataManager.Instance.CurrentPatientLink.Status.InPacuTime) < 0)
            {
                MessageBoxCommon.ShowDialog("开始时间应大于入复苏室时间", MessageBoxCommon.OK);
                return false;
            }
            if (DataManager.Instance.CurrentPatientLink.Status.OutPacuTime != new DateTime() && PatientDrugsModelCopy.BeginTime.CompareTo(DataManager.Instance.CurrentPatientLink.Status.OutPacuTime) > 0)
            {
                MessageBoxCommon.ShowDialog("开始时间应小于出复苏室时间", MessageBoxCommon.OK);
                return false;
            }
            return true;
        }

        //删除一条用药记录

        public void DeletePatientDrug()
        {
            PatientDrugsModelCopy.Status = "invalid";
            OperationDataPool.Instance.CurOperationData.DrugsDataCache.AddAndUpdateExe(PatientDrugsModelCopy);
            RefreshYao();
        }
        public void RefreshYao()
        {
            for (int i = 1; i <= DataManager.Instance.CurrentPatientLink.Status.PacuPage; i++)
            {
                //刷新单次用药与事件一栏
                (DataManager.Instance.PacuRecordCtrl.DataContext as PacuRecordCtrlViewModel).PacuRecordCtrlViewModels[i].PacuEventAndMedicineCtrlViewModel.Refresh();
                //刷新标记一栏
                (DataManager.Instance.PacuRecordCtrl.DataContext as PacuRecordCtrlViewModel).PacuRecordCtrlViewModels[i].PacuOperStatusItemCtrlViewModel.Refresh();
            }
            //OperationDetailsViewModel.Instance.Refresh();
        }
        #endregion

        #region EventHandlers
        private void Type_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            CommonTypeCellCtrl type = sender as CommonTypeCellCtrl;
            SelectedDrugGroupType = type.Tag as ConfigDrugGroupTypesModel;
            GetDisplayDrugCtrlList(SelectedDrugGroupType.Code);
        }

        private void Drug_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            CustomEDBtnCtrl ctrl = sender as CustomEDBtnCtrl;
        }

        public void Excute(string commond)
        {
            DataManager.Instance.IsNotNeedSaveData = false;
            switch (commond)
            {
                case "Delete":
                    {
                        DeletePatientDrug();
                        DrugAndEventWindow.Instance.CusContent = PacuSingleDrugConfigDialogCtrl.Instance;
                        DrugAndEventWindow.Instance.CloseWin(false);
                    }
                    break;
                case "Cancel":
                    {
                        PatientDrugsModelCopy = PatientDrugsModel.ObjectToJsonM().JsonToObjectM<PatientDrugsModel>();
                        DrugAndEventWindow.Instance.CusContent = PacuSingleDrugConfigDialogCtrl.Instance;
                        DrugAndEventWindow.Instance.CloseWin(false);
                    }
                    break;
                case "SaveAndContinue":
                    {
                        if (SavePatientDrug())
                        {
                            PatientDrugsModel = new PatientDrugsModel();
                            SetPatientDrug();
                        }
                    }
                    break;
                case "Save":
                    {
                        if (SavePatientDrug())
                        {
                            DrugAndEventWindow.Instance.CusContent = PacuSingleDrugConfigDialogCtrl.Instance;
                            DrugAndEventWindow.Instance.CloseWin(false);
                        }
                    }
                    break;
            }
        }


        private void Ctrl_Clicked(object sender, EventArgs e)
        {
            CustomEDBtnCtrl ctrl = sender as CustomEDBtnCtrl;
            ConfigDrugsModel cem = ctrl.Tag as ConfigDrugsModel;
            SelectedDrug = cem;
            try
            {
                if (ConfigDrugMethodsModelList.Where(O => O.Code != null && O.Code.Equals(SelectedDrug.Usage)).ToList() != null &&
                    ConfigDrugMethodsModelList.Where(O => O.Code != null && O.Code.Equals(SelectedDrug.Usage)).ToList().Count > 0)
                {
                    SelectedDrugMethod = ConfigDrugMethodsModelList.Where(O => O.Code != null && O.Code.Equals(SelectedDrug.Usage)).ToList().First();
                }
            }
            catch (Exception ex)
            {
                Common.LogHelper.Error(this.GetType(), ex);
            }
            AddDrug();
        }
        #endregion
    }
}
